# -*- coding: utf-8 -*-
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from common.helper import Helper
import json


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "平安女性关爱保险"

    # 生成产品信息
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(18, 61)],
                # 性别
                "gender": ["M"],
                # 保障期限
                "expire": ["1年"],
                # 交费方式
                "payType": ["年交"],
                # 乳腺癌保障保险
                "breastCancer": ["50000"],
                # 其他妇科癌症保险
                "womenOthCancer": ["50000"],
                # 计划
                "plan": ["佳人款"]
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 61)],
                # 性别
                "gender": ["M"],
                # 保障期限
                "expire": ["1年"],
                # 交费方式
                "payType": ["年交"],
                # 乳腺癌保障保险
                "breastCancer": ["100000"],
                # 其他妇科癌症保险
                "womenOthCancer": ["100000"],
                # 计划
                "plan": ["丽人款"]
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(18, 61)],
                # 性别
                "gender": ["M"],
                # 保障期限
                "expire": ["1年"],
                # 交费方式
                "payType": ["年交"],
                # 乳腺癌保障保险
                "breastCancer": ["100000"],
                # 其他妇科癌症保险
                "womenOthCancer": ["100000"],
                # 计划
                "plan": ["美人款"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["expire"], plan[k]["payType"],
                             plan[k]["breastCancer"], plan[k]["womenOthCancer"], plan[k]["plan"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                ))
                self.mysql._conn.commit()
                print(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                ))

    # 执行爬虫
    def requestJson(self, dt=None):

        if 18<=int(dt["year"])<40:
            subject = 10
        elif 40<= int(dt["year"])<50:
            subject = 11
        else:
            subject = 12
        data = {"insurantNum": [{"personNum": "1", "subjectType": subject}, {"personNum": "0", "subjectType": 11},
                                {"personNum": "0", "subjectType": 12}],
                "effectDate": {"addDays": "", "endDate": "2021-03-10", "beginDate": "2020-03-11"},
                "planPackage": {"marketProductCode": "MP03000432", "packageCode": "PK00006268", "packageType": "01"},
                "applyPeriod": {"term": 12, "termUnit": "M"}, "flowId": "I0N325eezc85mbAJ"}

        payload = json.dumps( data )

        r = requests.post( url =domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200 and "处理成功" in r.text :
            items = ( r.json()["quoteResult"] )
            if dt["plan"] == "佳人款":
                print("~~~~~~佳人款~~~~~~~")
                price = ( Helper.decimalParse( items[0]["actualPremium"] ))
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                self.mysql.updatePrice( data )

            elif dt["plan"] == "丽人款":
                print("~~~~~~丽人款~~~~~~~")
                price = (Helper.decimalParse(items[1]["actualPremium"]))
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                self.mysql.updatePrice( data )

            else:
                print("~~~~~~美人款~~~~~~~")
                price = (Helper.decimalParse(items[2]["actualPremium"]))
                data = {
                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }
                self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

